import {reactive, toRefs, watch} from "vue"
import {addMessage, delMessage, getMessages} from '../api/message'
import {ElMessage} from "element-plus"

export default () => {
  const state = reactive({
    messages: [],
    pagination: {
      total: 0,// 总条数
      pageSize: 15,// 分页大小
      currentPage: 0,// 当前页
      hasMore: false,//是否有下一页
    }
  });

  //删除消息
  const delMsg = async (id) => {
    let result = await delMessage(id)
    if (result.status === 'success') {
      const index = state.messages.findIndex(item => item.id == id)
      if (index !== -1) {
        state.messages.splice(index, 1)
      }
    } else {
      ElMessage.error('撤销失败')
    }
  }

  //新增消息
  const addMsg = (newMsg) => {
    state.messages.push(newMsg)
  }

  //清理消息相关的数据
  const reset = () => {
    state.pagination.currentPage = 0
    state.pagination.hasMore = false
    state.pagination.total = 0
    state.pagination.currentPage = 0
    state.messages = []
  }

  //获取消息列表数据
  const getMsgList = (conversationId, append = true) => {
    //如何不是以追加模式获取数据,需要重置相关的参数信息
    if (!append) {
      reset()
    }

    state.pagination.currentPage++
    getMessages(conversationId, state.pagination.currentPage, state.pagination.pageSize)
      .then(result => {
        let {messages, total} = result
        messages.reverse()
        //分页加载聊天记录时将记录以追加的方式插入,打开新的会话时以覆盖的方式插入记录
        state.messages = append ? [...messages, ...state.messages] : messages
        state.pagination.total = total
        //判断聊天记录是否还有下一页
        state.pagination.hasMore = state.messages.length < total
      })
  }

  return {
    ...toRefs(state),
    reset,
    addMsg,
    delMsg,
    getMsgList,
  }
}
